<?php

namespace App\Console\Commands;

use App\Models\Industry;
use App\Models\Template;
use App\Models\Article;
use Illuminate\Console\Command;

class ReorganizeTemplate extends Command {
    
    protected $signature = 'rt {batch}';
    protected $description = 'ReorganizeTemplate';
    
    public function __construct() {
        parent::__construct ();
    }
    
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function handle() {
        $this->error('开始整理加盟模板数据');
        $batch = $this->argument('batch');
        $industries = Industry::select('id', 'name')->get();
        foreach ($industries as $industry) {
            $templates = Article::where('hangye', $industry->name)->get();
            $this->saveTemplate($templates, $industry, $batch);
            unset($templates);
        }
    }
    
    public function saveTemplate($templates, $c, $batch) {
        $i = 1;
        $count = count($templates);
        foreach ($templates as $template) {
            $t = Template::where('industry_id', $c->id)->where('name', $template->title)->first();
            if(is_null($t)) {
                $t = Template::create([
                    'industry_id' => $c->id,
                    'name' => $template->title,
                    'batch' => $batch,
                    'content' => $template->content,
                ]);
                $this->info('行业：'.$c->name.':'.'模板：'.$i.'/'.$count.'  '.$t->name);
            }else {
                $this->info('行业：'.$c->name.':'.'模板：'.$i.'/'.$count.'  已存在');
            }
            $i++;
            unset($t);
            unset($template);
        }
    }
}
